package com.example.geoserverdemo;

import org.junit.jupiter.api.Test;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;

public class Img {

    @Test
    public void union(){
        String[] pics = new String[]{
                "src/main/resources/static/imgs/0.000-30.000(1).jpg",
                "src/main/resources/static/imgs/30.000-60.000(1).jpg",
                "src/main/resources/static/imgs/60.000-90.000(1).jpg",
                "src/main/resources/static/imgs/90.000-120.000(1).jpg"
        };
        String type = "png";
        String dst_pic = "src/main/resources/static/imgs/union.png";
        joinImageListHorizontal(pics, type, dst_pic);
        //https://www.codeleading.com/article/20232347978/
    }

    /**
     * 横向拼接一组（多张）图像
     * @param pics  将要拼接的图像
     * @param type 图像写入格式
     * @param dst_pic 图像写入路径
     * @return
     */
    public  boolean joinImageListHorizontal(String[] pics, String type, String dst_pic) {
        try {
            int len = pics.length;
            if (len < 1) {
                System.out.println("pics len < 1");
                return false;
            }
            File[] src = new File[len];
            BufferedImage[] images = new BufferedImage[len];
            int[][] imageArrays = new int[len][];
            for (int i = 0; i < len; i++) {
                src[i] = new File(pics[i]);
                images[i] = ImageIO.read(src[i]);
                int width = images[i].getWidth();
                int height = images[i].getHeight();
                imageArrays[i] = new int[width * height];// 从图片中读取RGB
                imageArrays[i] = images[i].getRGB(0, 0, width, height,  imageArrays[i], 0, width);
            }

            int dst_width = 0;
            int dst_height = images[0].getHeight();
            for (int i = 0; i < images.length; i++) {
                dst_height = dst_height > images[i].getHeight() ? dst_height : images[i].getHeight();
                dst_width += images[i].getWidth();
            }
            //System.out.println(dst_width);
            //System.out.println(dst_height);
            if (dst_height < 1) {
                System.out.println("dst_height < 1");
                return false;
            }
            /*
             * 生成新图片
             */
            BufferedImage ImageNew = new BufferedImage(dst_width, dst_height,  BufferedImage.TYPE_INT_RGB);
            int width_i = 0;
            for (int i = 0; i < images.length; i++) {
                ImageNew.setRGB(width_i, 0, images[i].getWidth(), dst_height,  imageArrays[i], 0, images[i].getWidth());
                width_i += images[i].getWidth();
            }
            File outFile = new File(dst_pic);
            ImageIO.write(ImageNew, type, outFile);// 写图片
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
